<template>
  <div class="login-box">
    <van-nav-bar class="top-nav-bar" title="登录" left-arrow>
      <template #left>
        <van-icon class-prefix="toutiao toutiao-guanbi guanbi" />
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field
        v-model="params.username"
        name="mobile"
        left-icon="toutiao-shouji toutiao-shouji toutiao"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="params.password"
        name="code"
        left-icon="toutiao-yanzhengma toutiao-yanzhengma toutiao"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      >
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <div class="code-btn" v-if="flag" @click.stop="sendCode">发送验证码</div>
    <div class="code-btn" v-else>{{ time }}s</div>
  </div>
</template>

<script>
import { codes, login } from '@/api/user'

export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      params: {
        username: '13800000001',
        password: '246810',
      },
      flag: true,
      time: 60,
    }
  },
  computed: {},
  watch: {},
  created() {},
  methods: {
    // 登录
    async onSubmit(values) {
      try {
        const {
          data: { data },
        } = await login(values)
        await this.$store.dispatch('user/setUserInfo', data)
        this.$toast.success('登录成功')
        this.$router.push('profile')
      } catch (error) {}
    },
    // 发送验证码
    async sendCode() {
      if (this.params.username !== '' && this.params.username) {
        try {
          const res = await codes(this.params.username)
          this.flag = false
          if (this.flag === false) {
            let settime = setInterval(() => {
              this.time--
              if (this.time === 0) {
                this.flag = true
                clearInterval(settime)
                this.time = 60
              }
            }, 1000)
          }
        } catch (error) {}
      }
    },
  },
}
</script>

<style scoped lang="less">
.top-nav-bar {
  background-color: #3296fa;
}
.guanbi {
  color: #fff;
  font-size: 12px;
}
::v-deep .van-ellipsis {
  color: #fff;
}

.login-box {
  position: relative;

  .code-btn {
    z-index: 1;
    top: 100px;
    right: 13px;
    position: absolute;
    width: 72px;
    height: 21px;
    background: #ededed;
    text-align: center;
    line-height: 21px;
    border: none;
    border-radius: 12px;
    padding: 0;
    font-size: 0.29333rem;
    color: #666;
  }
}
</style>
